package com.example.administrator.zhongyichou.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lichenyu on 2017/11/27.
 * 描述：
 */

public class ImageUtils {
    /**
     * @param photos 照片路径集合
     * @return 压缩后的图片集合
     */
    public static List<File> compressImages(final List<String> photos) {
        List<File> listFile = new ArrayList<>();
        for (int i = 0; i < photos.size(); i++) {
            try {
                File file = FileUtils.creatFilePath(FileUtils.getProjectFileImagePath(), System.currentTimeMillis() + "upload" + i + ".jpg");
                //压缩并将压缩后的图片存为upload.jpg
                FileOutputStream op = new FileOutputStream(file);
                op.write(getimage(photos.get(i)));
                op.close();
                listFile.add(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return listFile;
    }

    /**
     * 上传图片所需
     */
    public static byte[] getimage(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        //
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        double scal = 0.0;
        scal = (double) h / (double) w;
        float ww = 600f;
        float hh = (int) ((double) ww * scal);
        int be = 1;
        if (w > h && w > ww) {
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return compressImage1(bitmap);
    }

    /**
     * 质量压缩
     */
    public static byte[] compressImage1(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩,最多压缩十次
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);
            options -= 10;// 每次都减少10
            if (options == 10) {
                break;
            }
        }
        byte[] b = baos.toByteArray();
        try {
            baos.flush();
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return b;
    }
}
